import { defineStore } from "pinia";
import { useMenu } from "@/store/index.js";
import router from "@/router/index.js";
import routerList from "@/router/routerList.js";

export const useRoutesStore = defineStore("routes", {
  state: () => ({
    routes: [],
    addRoutes: [],
  }),
  actions: {
    handleRoutes() {
      // const routes = [];
      // const userInfoStore = useUserInfo();
      // const userInfo = userInfoStore.userInfo.permissions || [];
      // defineRoutes.forEach((item) => {
      //   if (item.permissions && item.permissions.length > 0) {
      //     item.permissions.forEach((keyWord) => {
      //       if (userInfo && userInfo.length > 0) {
      //         if (userInfo.includes(keyWord)) {
      //           routes.push(item);
      //         }
      //       }
      //     });
      //   }
      // });
      const useMenuStore = useMenu();
      this.routes = [];
      const menuList = useMenuStore.menuList
        .filter((item) => {
          return item.menuType !== "F";
        })
        .map((item) => {
          if (item.menuType === "M") {
            return {
              name: item.menuName,
              component: routerList["layout"],
              meta: {
                title: item.menuName,
                icon: item.icon,
              },
            };
          } else if (item.menuType === "C") {
            return {
              path: "/" + item.path.replace("/")[0],
              name: item.menuName,
              component: routerList["layout"],
              children: [
                {
                  path: item.path,
                  name: item.menuName,
                  component: routerList[item.path],
                  meta: {
                    title: item.menuName,
                    icon: item.icon,
                    permissions: item.perms,
                  },
                },
              ],
            };
          }
        });

      menuList.forEach((item) => {
        // 检查路由是否已存在
        if (item.path && !router.hasRoute(item.path)) {
          try {
            router.addRoute(item);
          } catch (error) {
            console.error("路由添加失败:", item, error);
          }
        }
      });
      let routes = router.getRoutes();
      this.routes = routes;
    },
    reset() {
      this.$reset();
      sessionStorage.removeItem("routes");
    },
  },
  persist: {
    enable: true,
    storage: sessionStorage,
  },
});

export default useRoutesStore;
